<template>
  <view class="main">
    <!--导航栏-->
    <action-bar :options="navOptions" />
    <view class="wrapper">
      <view class="handBtn">
        <view class="goback" @click="goback">取消</view>
        <view class="line"></view>
        <view class="delete" @click="retDraw">重写</view>
        <view class="line"></view>
        <view class="save" @click="saveCanvasAsImg">保存</view>
      </view>
      <view class="handCenter">
        <canvas class="handWriting" :disable-scroll="true" @touchstart="uploadScaleStart" @touchmove="uploadScaleMove"
          canvas-id="handWriting"></canvas>
      </view>

      <!-- 旋转签名 不予展示  因为是旋转 所以之前的高度 = 该宽度 -->
    </view>
    <view id="toRotateWriting">
      <canvas :style="{ width: canvasHeight + 'px', height: canvasWidth + 'px' }" canvas-id="toRotateWriting"></canvas>
    </view>
  </view>
</template>

<script>
import { baseApiUrl } from '@/config.js';
import { mapActions } from 'vuex';
export default {
  data() {
    return {
      navOptions: { // 导航栏配置参数
        statusBar: 'dark',
        left: {
          icon: 'back'
        },
        center: {
          title: '业主签字'
        }
      },
      canvasName: 'handWriting',
      ctx: '',
      startX: null,
      startY: null,
      canvasWidth: 0,
      canvasHeight: 0,
      selectColor: 'black',
      lineColor: '#1A1A1A', // 颜色
      lineSize: 5, // 笔记倍数
    };
  },
  onLoad() {
    this.ctx = uni.createCanvasContext("handWriting", this);
    this.$nextTick(() => {
      uni.createSelectorQuery().select('.handCenter').boundingClientRect(rect => {
        this.canvasWidth = rect.width;
        this.canvasHeight = rect.height;
        /* 将canvas背景设置为 白底，不设置  导出的canvas的背景为透明 */
        this.setCanvasBg('#fff');
      })
        .exec();
    });
  },
  methods: {
    ...mapActions({
      setFileUrl: 'reportSign/SETFILE_URL'
    }),
    // 笔迹开始
    uploadScaleStart(e) {
      this.startX = e.changedTouches[0].x
      this.startY = e.changedTouches[0].y
      //设置画笔参数
      //画笔颜色
      this.ctx.setStrokeStyle(this.lineColor)
      //设置线条粗细
      this.ctx.setLineWidth(this.lineSize)
      //设置线条的结束端点样式
      this.ctx.setLineCap("round") //'butt'、'round'、'square'
      //开始画笔
      this.ctx.beginPath()
    },
    // 笔迹移动
    uploadScaleMove(e) {
      //取点
      let temX = e.changedTouches[0].x
      let temY = e.changedTouches[0].y
      //画线条
      this.ctx.moveTo(this.startX, this.startY)
      this.ctx.lineTo(temX, temY)
      this.ctx.stroke()
      this.startX = temX
      this.startY = temY
      this.ctx.draw(true)
    },
    // 返回
    goback() {
      uni.navigateTo({
        url: '../../pages_workTableChild/reportSign/index',
        success: () => {

        }
      })
    },
    /**
     * 删除
     */
    retDraw() {
      this.ctx.clearRect(0, 0, 700, 730);
      this.ctx.draw();
      //设置canvas背景
      this.setCanvasBg('#fff');
    },
    /**
     * @param {Object} str
     * @param {Object} color
     * 选择颜色
     */
    selectColorEvent(str, color) {
      this.selectColor = str;
      this.lineColor = color;
    },
    //保存
    async saveCanvasAsImg() {
      let that = this
      // 获取token
      var token = this.$store.state.login.userInfo.token
      let firstUrl = await that.getImg('handWriting')
      await that.rotate(firstUrl)
      setTimeout(async () => {
        let secondUrl = await that.getImg('toRotateWriting')
        uni.uploadFile({
          url: baseApiUrl + "/common/upload",
          name: 'file',
          header: {
            Authorization: token
          },
          filePath: secondUrl, // 图片的临时路径
          success: uploadFileRes => {
            // 将上传成功的路径储存起来，方便保存时获取
            this.setFileUrl(JSON.parse(uploadFileRes.data).fileName)
            uni.navigateBack({
              delta: 1
            })
          },
          fail: err => {
            uni.showToast({
              title: err,
              icon: 'none',
              duration: 2000
            });
          }
        });
      }, 15);
    },

    // 将手写的转换成临时路径
    getImg(id) {
      return new Promise((resolve, reject) => {
        uni.canvasToTempFilePath({
          canvasId: id,
          fileType: 'png',
          quality: 1, //图片质量
          success: res => {
            resolve(res.tempFilePath)
          },
          fail: (err) => {
            console.log(err)
          }
        })
      })
    },

    // 将图片选装
    rotate(path) {
      return new Promise((resolve, reject) => {
        let rotatCtx = uni.createCanvasContext('toRotateWriting'); //创建绘图对象
        // 重新定位中心点
        rotatCtx.translate(0, this.canvasWidth);
        // 将画布逆时针旋转90度
        rotatCtx.rotate((-90 * Math.PI) / 180);
        // 将签字图片绘制进入Canvas
        rotatCtx.drawImage(path, 0, 0, this.canvasWidth, this.canvasHeight);
        // 保存后旋转后的结果
        rotatCtx.draw();
        resolve()
      })
    },

    //设置canvas背景色  不设置  导出的canvas的背景为透明
    //@params：字符串  color
    setCanvasBg(color) {

      /* 将canvas背景设置为 白底，不设置  导出的canvas的背景为透明 */
      //rect() 参数说明  矩形路径左上角的横坐标，左上角的纵坐标, 矩形路径的宽度, 矩形路径的高度
      //这里是 canvasHeight - 4 是因为下边盖住边框了，所以手动减了写
      this.ctx.rect(0, 0, this.canvasWidth, this.canvasHeight - 4);
      this.ctx.setFillStyle(color);
      this.ctx.fill(); //设置填充
      this.ctx.draw(); //开画
    }
  }
};
</script>

<style lang="scss">
#toRotateWriting {
  position: absolute;
  left: 100vw;
}

.main {
  height: auto;
  overflow: hidden;
}

.wrapper {
  width: 100%;
  height: 95vh;
  overflow: hidden;
  display: flex;
  align-content: center;
  flex-direction: row;
  justify-content: center;
  font-size: 28rpx;
}

.handWriting {
  width: 100%;
  height: 95vh;
}

.handRight {
  display: inline-flex;
  align-items: center;
}

.handCenter {
  flex: 5;
  overflow: hidden;
  box-sizing: border-box;
}

.handBtn {
  height: 95vh;
  width: 80rpx;
  background: #f4f5f5;

  .goback {
    margin: 200rpx auto;
    font-size: 30rpx;
    font-family: Source Han Sans CN;
    font-weight: 400;
    color: #333333;
    line-height: 36rpx;
    transform: rotate(90deg);
  }

  .line {
    width: 100%;
    height: 2rpx;
    background: #c1c1c1;
  }

  .delete {
    margin: 200rpx auto;
    font-size: 30rpx;
    font-family: Source Han Sans CN;
    font-weight: 400;
    color: #e61717;
    line-height: 36rpx;
    transform: rotate(90deg);
  }

  .save {
    margin: 200rpx auto;
    font-size: 30rpx;
    font-family: Source Han Sans CN;
    font-weight: 400;
    color: #335ac6;
    line-height: 36rpx;
    transform: rotate(90deg);
  }
}
</style>
